package com.discuz.post;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.EntityUtils;


@SuppressWarnings("deprecation")
public class DiscuzAutoPost {

	

	private String DOMAIN = null;
	private int BOARD_ID = -1;
	private PostConfig config = new PostConfig(); 
	private HiddenForm hf = new HiddenForm();
	

	/**
	 * @param title 
	 * @param content
	 * @param File [] images
	 * @param File [] atts
	 * 
	 * @return void
	 * 
	 **/
	public  void post(String title, String content,File [] images,File [] atts)
			throws IllegalStateException, IOException {

		String NEW_POST_URL = "forum.php?mod=post&action=newthread&fid=" + BOARD_ID;
		
		//get hidden form 
		hf = getHiddenForm(DOMAIN + NEW_POST_URL);
		
		boolean isHaveAtt = false;
		//image upload
		if(images != null){
			isHaveAtt = true;
			
			for(File ima : images){
				upload(ima,true);
				
			}
			System.out.println("upload image complete. size = "+images.length);
		}
		
		//upload att
		if(atts != null){
			isHaveAtt = true;
			for(File f : atts){
				upload(f,false);
			}
			System.out.println("upload att complete. size = "+atts.length);
		}
		
		//获取附件id
		if(isHaveAtt == true){
			getAttsID(DOMAIN + NEW_POST_URL,hf);
		}
		
		//Message request
		final String sumbitURL = 
				DOMAIN +"forum.php?mod=post&action=newthread&fid="
				+ BOARD_ID + "&extra=&topicsubmit=yes";
		HttpPost post = new HttpPost(sumbitURL);
		post.setHeader("Cookie", HttpUtils.checkCookie());
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		
		builder.addTextBody("formhash", hf.formhash);
		builder.addTextBody("wysiwyg",  hf.wysiwyg);
		builder.addTextBody("posttime", hf.posttime);
		builder.addTextBody("subject", title);
		builder.addTextBody("message", content);
		builder.addTextBody("allownoticeauthor", "1");
		//	
		builder.addTextBody("readperm",config.getReadperm());
		builder.addTextBody("price", config.getPrice());
		
		//append file att
		for(String e : hf.attAid){
			builder.addTextBody("attachnew["+e+"][description...","");
			builder.addTextBody("attachnew["+e+"][price]",config.getAttPrice());
			builder.addTextBody("attachnew["+e+"][readperm]",config.getAttReadperm());
			builder.addTextBody("unused[]", e);
		}
		
		//append image att
		for(String e : hf.imageAid){
			builder.addTextBody("attachnew["+e+"][description...","");
			builder.addTextBody("unused[]", e);
			
		}
		
		final HttpEntity yourEntity = builder.build();
		post.setEntity(yourEntity);

		HttpResponse  response = HttpUtils.get().execute(post);
		HttpEntity entity = response.getEntity();
		EntityUtils.consume(entity);
		

	}
	
	private HiddenForm getAttsID(String url,HiddenForm hf) {
		HttpGet httpget = new HttpGet(url);

		httpget.setHeader("Cookie", HttpUtils.checkCookie());
		String entityString = null;
		HttpResponse response = null;
		try {
			 response = HttpUtils.get().execute(httpget);
			HttpEntity entity = response.getEntity();
			entityString = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		hf.attAid = RegHelper.matchAtt(entityString);
		
		hf.imageAid = RegHelper.matchImage(entityString);
		
		return hf;
	}

	public  void upload(File file,boolean isImage)
			throws IllegalStateException, IOException {
		// 发文请求
		final String sumbitURL = 
				DOMAIN +"misc.php?mod=swfupload&action=swfupload&operation=upload&fid="+BOARD_ID;
		HttpPost post = new HttpPost(sumbitURL);

		post.setHeader("Cookie", HttpUtils.checkCookie());
		//-------------------------------------------
		post.setHeader("enctype", "multipart/form-data");
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
		
		builder.addTextBody("uid", hf.uid);
		builder.addTextBody("hash",  hf.imagehash);
		if(isImage){
			builder.addTextBody("type",  "image");
		}
		//image input Filedata
		builder.addPart("Filedata", new FileBody(file));
		
		
		final HttpEntity entity = builder.build();
		post.setEntity(entity);
		HttpResponse response = HttpUtils.get().execute(post);
		HttpEntity rqEntity = response.getEntity();
		EntityUtils.consume(rqEntity);
		
	}
	
	

	

	private  HiddenForm getHiddenForm(String url) {
		
		HttpGet httpget = new HttpGet(url);

		httpget.setHeader("Cookie", HttpUtils.checkCookie());
		String entityString = null;
		try {
			HttpResponse response = HttpUtils.get().execute(httpget);
			HttpEntity entity = response.getEntity();
			entityString = EntityUtils.toString(entity);
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		int pos = entityString.indexOf("id=\"formhash\" value=");
		hf.formhash = entityString.substring(pos + 21, pos + 21 + 8);

		pos = entityString.indexOf("id=\"posttime\" value=");
		hf.posttime = entityString.substring(pos + 21, pos + 21 + 10);

		pos = entityString.indexOf("id=\"e_mode\" value=");
		hf.wysiwyg = entityString.substring(pos + 19, pos + 19 + 1);
		
		//image 
		pos = entityString.indexOf("name=\"uid\" value=");
		hf.uid = entityString.substring(pos + 18, pos + 18 + 1);
		
		pos = entityString.indexOf("name=\"hash\" value=");
		hf.imagehash = entityString.substring(pos + 19, pos + 19 + 32);

		return hf;
	}

	

	public DiscuzAutoPost setDomain(String domain) {
		this.DOMAIN = domain;
		return this;
	}
	
	public DiscuzAutoPost setboard(int board) {
		this.BOARD_ID = board;
		return this;
	}



}
